package com.lv.suyiyong.hfr.ui

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.view.View.OnClickListener
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.MyUtils
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.dialog.FirstDialog
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.room.category.SpuCategoryDbHelper
import com.lv.service.room.splash.AdSplashDbHelper
import com.lv.service.utils.YgxAroutPageKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.YgxApplication
import com.lv.suyiyong.hfr.databinding.ActivitySplashBinding
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.system.exitProcess

@Route(path = ARoutUtils.SplashActivity)
class SplashActivity : BaseActivity<ActivitySplashBinding>(), OnClickListener {
    private var isOpend = false
    private var isFristLoad = false
    private var mTimes = 0
    private val timer = Timer()
    override fun getLayoutRes() = R.layout.activity_splash
    override fun initView() {
        super.initView()
        mBinding.apply {
            llTime.setOnClickListener {
                handler.removeCallbacksAndMessages(null)
                redirectTo()
            }
            tvOpen.setOnClickListener(this@SplashActivity)
        }
        // 隐藏状态栏
        initStatusBar(this, true, false)
    }

    override fun initData() {
        super.initData()
        isOpend = SPStaticUtils.getBoolean(Constants.ISOPEND, false)//是否打开过App
        setDialog()
    }


    override fun initConfig() {
        super.initConfig()
//        SalerDbHelper.deleteAllSaler(this@SplashActivity)
//        SuerDbHelper.deleteAllSaler(this@SplashActivity)
        CategoryDbHelper.deleteAllCategory(this@SplashActivity)
//        CardCategoryDbHelper.deleteAllCategory(this@SplashActivity)
        AddressDbHelper.deleteAllAddress(this@SplashActivity)
        SpuCategoryDbHelper.deleteAllCategory(this@SplashActivity)
//        CardAddressDbHelper.deleteAllAddress(this@SplashActivity)
//        CardColorDbHelper.deleteAllCardColor(this@SplashActivity)
//        NewTelCategoryDbHelper.deleteAllCategory(this@SplashActivity)
//        NewTelCategoryCityDbHelper.deleteAllCategory(this@SplashActivity)
    }

    private fun initAD() {
        lifecycleScope.launch {
            val adSplash = AdSplashDbHelper.getFindAdDataBeanSuspend(this@SplashActivity)
            if (adSplash != null) {
                mTimes = (YgxUtilsKt.parseBannerTime(adSplash.startup) / 1000).toInt()
                if (mTimes == 0) {
                    redirectTo()
                } else {
                    mBinding.llTime.visibility = View.VISIBLE
                    mBinding.mTimes = mTimes
                    //等待时间一秒，停顿时间一秒
                    handler.sendEmptyMessageDelayed(1, 100)
                    if (adSplash.tag == "-1") {//新年
                        loadNewYearAd()
                        mBinding.llTime.setBackgroundResource(com.lv.common.R.drawable.bg_tran_20_fff_13)
                    } else {
                        mBinding.tvGopage.visibility = View.VISIBLE
                        mBinding.adContainer.LoadSrc(adSplash.image)
                        mBinding.tvGopage.setOnClickListener {
                            handler.removeCallbacksAndMessages(null)
                            AdSplashDbHelper.deleteAllAdDataBean(this@SplashActivity)
                            YgxAroutPageKt.startMain(
                                0, this@SplashActivity, adSplash.tag,
                                adSplash.url, adId = adSplash.id
                            )
                        }
                    }

                }
//                AdSplashDbHelper.deleteAllAdDataBean(this@SplashActivity)

            } else {
                redirectTo()
            }

        }

    }

    /**
     * 跳转到...
     */
    private fun redirectTo() {
        AdSplashDbHelper.deleteAllAdDataBean(this@SplashActivity)
        ARouter.getInstance().build(ARoutUtils.HomeActivityURL).navigation()
        finish()
    }

    fun setDialog() {
        val chatToken = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
        isFristLoad = SPStaticUtils.getBoolean(Constants.ISFRISTLOAD, false)
        if ("aaa" == chatToken) {
            val randomString: String = MyUtils.getRandomString(16)
            SPStaticUtils.put(Constants.KEY_CHAT_TOKEN, randomString)
        }
        if (isFristLoad) {
            initAD()
        } else {
            val firstDialog: FirstDialog = FirstDialog(this)
            firstDialog.setCanceledOnTouchOutside(false)
            firstDialog.show()
            firstDialog.setLeftBtnClickListener {
                firstDialog.dismiss()
                ActivityUtils.finishAllActivities()
            }
            firstDialog.setRightBtnClickListener {
//                isFristLoad = true
//                isOpend = true
                if (isOpend) {//打开过
                    initAD()
                } else {
                    ARouter.getInstance().build(ARoutUtils.WelComeActivityURL).navigation()
                    firstDialog.dismiss()
                    finish()
                }
            }
        }
    }

    private val handler: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> if (mTimes == 1) {
                    removeCallbacksAndMessages(null)
                    redirectTo()
                } else {
                    mTimes--
                    mBinding.mTimes = mTimes
                    if (mTimes < 0) {
                        timer.cancel()
                        //倒计时到 0 隐藏字体
                        mBinding.llTime.visibility = View.GONE
                    }
                    removeCallbacksAndMessages(null)
                    sendEmptyMessageDelayed(1, 1000)

                }

                else -> {}
            }
        }
    }


    private fun loadNewYearAd() {
        mBinding.ivLogo.visibility = View.GONE
        mBinding.ivLogoTag.visibility = View.VISIBLE
        mBinding.clContainerNew.visibility = View.VISIBLE
        mBinding.ivLeftBottom.visibility = View.VISIBLE
        mBinding.ivRightBottom.visibility = View.VISIBLE
        mBinding.ivRightTop.visibility = View.VISIBLE
        val nowDateTime = TimeUtil.getNowDateTime("yyyy-MM-dd")
//        val nowDateTime = "2025-01-29"
        when (nowDateTime) {
            "2025-01-28" -> {//除夕
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_30)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_30)
            }

            "2025-01-29" -> {//初一
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_1)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_1)

            }

            "2025-01-30" -> {//初二
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_2)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_2)
            }

            "2025-01-31" -> {//初三
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_3)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_3)
            }

            "2025-02-01" -> {//初四
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_4)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_4)
            }

            "2025-02-02" -> {//初五
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_5)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_5)

            }

            "2025-02-03" -> {//初六
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_6)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_6)

            }

            "2025-02-04" -> {//初七
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_7)
//                mBinding.ivLeftBottom.setImageResource(R.drawable.ic_lunch_right_bottom_7)
            }

            else -> {
                mBinding.ivLogo.visibility = View.GONE
                mBinding.ivLeftBottom.visibility = View.GONE
                mBinding.ivRightBottom.visibility = View.GONE
                mBinding.ivRightTop.visibility = View.GONE
                mBinding.ivLogoTag.visibility = View.GONE
                mBinding.clContainerNew.visibility = View.GONE
                mBinding.ivTopTag.visibility = View.VISIBLE
                mBinding.tvOpen.visibility = View.VISIBLE
                mBinding.ivBottomTag.visibility = View.VISIBLE
//                mBinding.adContainer.setImageResource(R.drawable.bg_new_year_ad)
//                mBinding.ivBottomTag.setImageResource(R.drawable.text_bottom_new_year_ad)
            }

        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_open -> {
                handler.removeCallbacksAndMessages(null)
                redirectTo()
            }
        }
    }


    private fun exit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            handler.removeCallbacksAndMessages(null)
            YgxApplication.getInstance().exit()
            finish()
        }
    }

    private var exitTime: Long = 0L
    override fun onBackPressed() {
        super.onBackPressed()
        exitProcess(0)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }


}